package blackspire.service.issues;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.transaction.annotation.Transactional;

import blackspire.model.issue.Issue;

@Transactional
public class IssuesServiceImpl implements IssuesService
{
	private EntityManager em;

	@PersistenceContext
	public void setEntityManager(EntityManager em)
	{
		this.em = em;
	}

	@SuppressWarnings("unchecked")
	public List<Issue> findAll()
	{
		Query query = getEntityManager().createQuery("select i FROM Issue i");
		return query.getResultList();
	}

	public void save(Issue issue)
	{
		if (issue.getId() == null)
		{
			// new
			em.persist(issue);
		} else
		{
			// update
			em.merge(issue);
		}
	}

	public void remove(int id)
	{
		Issue issue = find(id);
		if (issue != null)
		{
			em.remove(issue);
		}
	}

	private EntityManager getEntityManager()
	{
		return em;
	}

	public Issue find(int id)
	{
		return em.find(Issue.class, id);
	}

}
